package com.group.itms.routes.activities;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.group.itms.routes.R;
import com.group.itms.routes.activities.MainActivity.LocationAdapter.Callbacks;
import com.group.itms.routes.data.Advertisement;
import com.group.itms.routes.data.BObject;
import com.group.itms.routes.data.ObjectType;
import com.group.itms.routes.services.PingService;
import com.group.itms.routes.services.SyncService;
import com.j256.ormlite.dao.Dao;

public class MainActivity extends BaseActivity {

	public static final String TAG = MainActivity.class.getSimpleName();

	private Button mTopicsButton;
	private LinearLayout mAdContainer;

	private LocationAdapter mLocationAdapter;
	
//	private Timer mAdTimer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initialiseViews();
		setListeners();
		setAsHome(); // this is home activity
		ListView locationsListView = (ListView) findViewById(R.id.lvLocations);
		mLocationAdapter = new LocationAdapter(this, getCallbacks());
		locationsListView.setAdapter(mLocationAdapter);
		loadLocations();
		syncIfNeeded();
		setupAds();
	}

//	private void setupAds() {
//		if (mAdTimer == null) {
//			mAdTimer = new Timer();
//			mAdTimer.scheduleAtFixedRate(new ShuffleAdTask(), 0, 20 * 1000);
//		}
//	}
	
	private void setupAds() {
		initAds(getHardCodedAds());
	}

	private void loadLocations() {
		List<BObject> locations = queryForLocations();
		Collections.sort(locations, new Comparator<BObject>() {

			@Override
			public int compare(BObject lhs, BObject rhs) {
				return lhs.getObjInd().compareTo(rhs.getObjInd());
			}
		});
		mLocationAdapter.setLocations(locations);
	}

	private void initialiseViews() {
		mTopicsButton = (Button) findViewById(R.id.btnTopics);
		mAdContainer = (LinearLayout) findViewById(R.id.llAdvContainer);
	}

	private Callbacks getCallbacks() {
		return new Callbacks() {

			@Override
			public void onShowOnMapClicked(BObject location) {
				Context ctx = MainActivity.this;
				startActivity(NewMapActivity.getIntent(ctx, location.getId()));
			}

			@Override
			public void onShowDetailsClicked(BObject location) {
				Context ctx = MainActivity.this;
				startActivity(LocationDetailActivity.getIntent(ctx, location.getId()), true);
			}
		};
	}
	
	private void setListeners() {
		for (int i = 0; i < mAdContainer.getChildCount(); i++) {
			mAdContainer.getChildAt(i).setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Object tag = v.getTag();
							if (tag != null) {
								Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tag.toString()));
								startActivity(intent);
							}
						}
					});
		}

		mTopicsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(TopicsActivity.class);
			}
		});
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		syncIfNeeded();
	}

	private void syncIfNeeded() {
		if (!PingService.sRunning) {
			startService(new Intent(this, PingService.class));
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (mSyncManager.isSyncing()) {
			mSyncManager.registerSyncListener(this);
			Log.i(TAG, "Registered as a listener");
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_sync:
			mSyncManager.startSync();
			mSyncManager.registerSyncListener(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onSyncDone(int statusCode) {
		super.onSyncDone(statusCode);
		if (statusCode == SyncService.SYNC_OK) {
			loadLocations();
//			shuffleAdvertisements();
		}
	}
	
	@SuppressWarnings("unused")
	private void shuffleAdvertisements() {
		List<Advertisement> adList;
		try {
			adList = getHelper().getAdvertDao().queryForEq(Advertisement.IS_ACTIVE, true);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		Collections.shuffle(adList);
		initAds(adList);	
	}

	private void initAds(List<Advertisement> adList) {
		int n = mAdContainer.getChildCount();
		for (int i = 0; i < n; i++) {
			if (i < adList.size()) {
				Advertisement ad = adList.get(i);
				final ImageView adImage = (ImageView) mAdContainer.getChildAt(i);
//				adImage.setOnTouchListener(new OnTouchListener() {
//					
//					@Override
//					public boolean onTouch(View v, MotionEvent event) {
//						switch (event.getAction()) {
//						case MotionEvent.ACTION_DOWN:
//							adImage.setBackgroundColor(0xEE447799);
//							adImage.setImageAlpha(80);
//							break;
//						case MotionEvent.ACTION_UP:
//							adImage.setBackgroundColor(Color.WHITE);
//							adImage.setImageAlpha(255);
//							break;
//						}
//						return false;
//					}
//				});
				adImage.setTag(ad.getUrl());
				adImage.setImageResource(ad.getImageResId());
			}
		}
	}
	
	private List<Advertisement> getHardCodedAds() {
		List<Advertisement> ads = new ArrayList<Advertisement>();
		ads.add(newAd("https://www.giz.de/", R.drawable.ad_giz));
		ads.add(newAd("http://www.iliauni.edu.ge/", R.drawable.ad_ilia));
		ads.add(newAd("http://www.ecotourism.ge/", R.drawable.ad_ecoturism));
		return ads;
	}
	
	private Advertisement newAd(String url, int photoResId) {
		Advertisement ad = new Advertisement();
		ad.setUrl(url);
		ad.setImageResId(photoResId);
		return ad;
	}
	
	@Override
	protected String getTag() {
		return TAG;
	}
	
	private List<BObject> queryForLocations() {
		Dao<BObject, Integer> dao = getHelper().getObjectDao();
		try {
			return dao.queryBuilder()
					.where()
					.eq(BObject.TYPE, ObjectType.LOCATION)
					.and()
					.eq(BObject.IS_ACTIVE, true)
					.query();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mSyncManager.unregisterSyncListener(this);
//		if (mAdTimer != null) {
//			mAdTimer.cancel();
//			mAdTimer = null;
//		}
	}
	
	static class LocationAdapter extends ArrayAdapter<BObject> {

		private Callbacks mCallback;

		private OnClickListener mCallbackDispatcher = new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mCallback != null) {
					BObject location = (BObject) v.getTag();
					if (v instanceof TextView) {
						mCallback.onShowDetailsClicked(location);
					} else if (v instanceof ImageView) {
						mCallback.onShowOnMapClicked(location);
					} else {
						throw new RuntimeException("this should not happen");
					}
				}
			}
		};

		public LocationAdapter(Context context, Callbacks callback) {
			super(context, 0);
			mCallback = callback;
		}

		public LocationAdapter(Context context, Callbacks callback, List<BObject> list) {
			super(context, 0, list);
			mCallback = callback;
		}

		public void setLocations(List<BObject> locations) {
			setNotifyOnChange(false);
			clear();
			setNotifyOnChange(true);
			addAll(locations);
		}

		public void addAll(List<BObject> locations) {
			setNotifyOnChange(false);
			for (BObject loc : locations) {
				add(loc);
			}
			setNotifyOnChange(true);
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView != null ? convertView : inflateLocationView();
			BObject location = getItem(position);
			TextView name = (TextView) v.findViewById(R.id.name);
			ImageView showOnMap = (ImageView) v.findViewById(R.id.show_on_map);
			name.setText(location.getIndName(". "));
			// set tags
			name.setTag(location);
			showOnMap.setTag(location);
			// register listeners
			name.setOnClickListener(mCallbackDispatcher);
			showOnMap.setOnClickListener(mCallbackDispatcher);
			return v;
		}

		private View inflateLocationView() {
			return LayoutInflater.from(getContext()).inflate(R.layout.location,
					null);
		}

		public interface Callbacks {
			void onShowDetailsClicked(BObject location);

			void onShowOnMapClicked(BObject location);
		}

	}

//	class ShuffleAdTask extends TimerTask {
//		
//		@Override
//		public void run() {
//			runOnUiThread(new Runnable() {
//				
//				@Override
//				public void run() {
//					shuffleAdvertisements();
//				}
//			});
//		}
//		
//	}
}
